<template>
    <view class="playbill">
        <canvas canvas-id="poster" class="hidCvs"></canvas>
        <swiper
            class="swiper"
            indicator-color='#999'
            indicator-active-color='#333'
            :indicator-dots="true"
            :autoplay="false"
            previousMargin="30px"
            next-margin="80px"
            :circular="true"
            :current="swiperIndex"
            @change="onSwiperChange"
           >
            <swiper-item v-for="(item, index) of posterslist" :key="index" class="swiper_t" :class="{active :swiperIndex == index }" >
                <view class="goods_info_box"   >
                <cdn-img class="img" :src="item.path" mode="scaleToFill"></cdn-img>
                <view class="sss">
                    <image class="poster_canvas" :src="code" mode="scaleToFill"></image>
                </view>
                </view>
            </swiper-item>
        </swiper>
        <view>
            <view class="posters" @click="toshare()">保存海报</view>
        </view>
    </view>
</template>
<script>
import QR from '@/utils/wxqrcode.js'; // 二维码生成器
import { useUserStore, useConfigStore } from '@/stores'
import { useDidShow, useLoad,showLoading, useReady, downloadFile, canvasToTempFilePath, createCanvasContext, hideLoading, showToast  } from '@tarojs/taro'
import { reactive ,toRefs} from 'vue'
export default {
    setup() {
        const user = useUserStore()
        const config = useConfigStore()
        const state = reactive({
            code:'', //二维码
            posterImgs: [], // 海报下载
            swiperIndex: 0, // 索引
            posterslist:[
                {path: "https://static.douyintuoke.cn/static/img/poster/03.png"},
                {path: "https://static.douyintuoke.cn/static/img/poster/02.png?v=1"},
                {path: "https://static.douyintuoke.cn/static/img/poster/01.png"},
            ]
        })
    useLoad(async(query) => {
          let img = QR.createQrCodeImg(user.tiktok.mini_link, {
                size: parseInt(300), //二维码大小
            });
            state.code = img;
			// 开启分享
			wx.showShareMenu({
				withShareTicket: true,
				menus: ['shareAppMessage', 'shareTimeline'],
			})
    });
       // 轮播图变化
     function onSwiperChange(e) {
      this.swiperIndex = e.detail.current;
    }
        // 创建海报
    function createPoster() {
        return new Promise((resolve, reject) => {
            showLoading({title: '海报生成中', mask: true});
            const ctx = wx.createCanvasContext('poster')
            ctx.fillRect(0, 0, 375, 669);
            ctx.setFillStyle('#FFF');
            downloadFile({
                // url: 'https://static.douyintuoke.cn/static/img/poster/03.png', // 海报图
                url: state.posterslist[state.swiperIndex].path,
                success: async (res) => {
                    if (res.statusCode === 200) {
                        const base64Str = state.code.split(',')[1];
                        ctx.drawImage(res.tempFilePath, 0, 0, 375, 669);  //绘制海报
                        const codeImg = await this.writeFileToLocal(base64Str);
                        ctx.drawImage(codeImg, 130, 480, 120, 120);  //二维码
                        // ctx.strokeStyle = '#38f';
                        // ctx.fillRect(110, 455, 110, 110);
                        // ctx.fillStyle = 'orange';
                        ctx.shadowColor = '#FFFFFF';
                        ctx.lineWidth = 5;
                        ctx.strokeStyle = '#FFFFFF';
                        ctx.strokeRect(130, 480, 120, 120);

                        ctx.draw(false, () => {
                            wx.canvasToTempFilePath({
                                canvasId: 'poster',
                                width: 375,
                                height: 669,
                                success: (img) => {
                                    if (this.posterImgs[this.swiperIndex]) {
                                        this.posterImgs[this.swiperIndex].temporary = img.tempFilePath;
                                    } else {
                                        this.posterImgs[this.swiperIndex] = {
                                            temporary: img.tempFilePath,
                                        };
                                    }
                                    console.log('海报制作成功！');
                                    resolve(img.tempFilePath);
                                    hideLoading();
                                },
                                fail: () => {
                                    hideLoading();
                                    reject();
                                },
                            });
                        });
                    } else {
                        hideLoading();
                        showToast({
                            title: '海报制作失败，图片下载失败',
                            icon: 'none',
                        });
                    }
                },
                fail: (err) => {
                    hideLoading();
                    showToast({
                    title: '海报制作失败，图片下载失败',
                    icon: 'none',
                    });
                },
            });
        });
    }
    // 底部弹窗 微信 分享好友  分享朋友圈  保存海报到本地
  async function toshare() {
        var imgUrl = ''
        // imgUrl = await this.createPoster();
        if ( this.posterImgs[this.swiperIndex] && this.posterImgs[this.swiperIndex].temporary ) {
        imgUrl = await this.posterImgs[this.swiperIndex].temporary;
      } else {
        imgUrl = await this.createPoster();
      }
        wx.showShareImageMenu({
            withShareTicket: true,
            path: imgUrl, // 要分享的图片地址，必须为本地路径或临时路径
            success: (res)=>{
                console.log('分享或者下载成功',res);
            }
        })
  }   
 function  writeFileToLocal(base64Image){
		return new Promise((resolve,reject)=>{
			const fsm = wx.getFileSystemManager();
			const FILE_BASE_NAME = 'tmp_base64src';
			const format = 'png';
			// const timestamp = (new Date()).getTime();
			const str = String(this.user.info.id) ? this.user.info.id : ''; 
			const buffer = wx.base64ToArrayBuffer(base64Image)
			const filePath = `${wx.env.USER_DATA_PATH}/${str}share.${format}`;
			
			fsm.writeFile({
				filePath,
				data: buffer,
				encoding: 'binary',
				success(res) {
					resolve(filePath);
				},
				fail(e){
					reject(e);
				}
			})
		})
	}
 return {
        ...toRefs(state),
        config,
        user,
        createPoster,
        toshare,
        writeFileToLocal,
        onSwiperChange
          
		}
},

    onShareAppMessage(res){
        const { share_title, share_img } =this.config.oemInfo
        return {
            title: share_title,
            path: `/pages/home/index?from_id=${this.user.info.id}`,
            imageUrl: share_img,
        }
    },
    onShareTimeline(){
        const { share_title, share_img } = this.config.oemInfo
        return {
            title: share_title,
            imageUrl: share_img,
            query: `from_id=${this.user.info.id}`
        }
	},

}
</script>
<style lang="scss">
.playbill{
    position: relative;
    // line-height: 150px;
    .swiper_t{
    height: 339px !important;
    position: relative;
    margin-top: 30%;
    }
    .swiper{
        min-height: 70vh;
        .img{
        width: 221px;
        height: 100%;
        position: absolute;
        left: 20%;
        }
    .active{
        height: 393px !important;
        margin-top: 20% !important;
    }
    }
    .posters{
        height: 32px;
        width: 140px;
        font-size: 14px;
        text-align: center;
        color: #FFFFFF;
        padding-top: 8px; 
        border-radius: 12px;
        background: linear-gradient(0deg,#395df4 0%, #73b5ff 100%);
        box-shadow: 1.25px 2.17px 0px 2.5px rgba(20,20,211,0.75); 
        position: absolute;
        left: 30%;
        margin-top: 23px;
        }
        .sss{
            width: 77px;
            height: 77px;
            top: 70%;
            left: 42%;
            position: fixed;
            background-color: #FFFFFF;
            border-radius: 5px;
            .poster_canvas {
                width: 70px;
                height: 70px;
                top: 71%;
                left: 43%;
                position: fixed;
            }
        }
       

}
// swiper .wx-swiper-dots .wx-swiper-dot{
//   width: 19px;    
//   height: 6px;  
//   border-radius: 4px;  
//   position: relative;
//   line-height: 150px;
// }

.hidCvs{
    width: 375px;
    height: 669px;
    position: fixed;
    top: -10000rpx;
    left: 0rpx;
}
</style>